import urlConfig from './config.js'
import store from './../store'

const request = {}
const headers = {}
const PORT1 = '/baseinfo';

const isChinaMobile = /^134[0-8]\d{7}$|^(?:13[5-9]|147|15[0-27-9]|178|18[2-478])\d{8}$/;
const isChinaUnion = /^(?:13[0-2]|145|15[56]|176|18[56])\d{8}$/;
const isChinaTelcom = /^(?:133|153|177|18[019])\d{8}$/; //1349号段 
const isOtherTelphone = /^170([059])\d{7}$/; //其他运营商

const utils = {
    checkMobile: function (telphone) {
        if (telphone.length !== 11) {
            return this.setReturnJson(false, '未检测到正确的手机号码');
        } else {
            if (isChinaMobile.test(telphone)) {
                return this.setReturnJson(true, '移动', {
                    name: 'ChinaMobile'
                });
            } else if (isChinaUnion.test(telphone)) {
                return this.setReturnJson(true, '联通', {
                    name: 'ChinaUnion'
                });
            } else if (isChinaTelcom.test(telphone)) {
                return this.setReturnJson(true, '电信', {
                    name: 'ChinaTelcom'
                });
            } else if (isOtherTelphone.test(telphone)) {
                var num = isOtherTelphone.exec(telphone);
                return this.setReturnJson(true, '', {
                    name: ''
                });
            } else {
                return this.setReturnJson(false, '未检测到正确的手机号码');
            }
        }
    },
    setReturnJson: function (status, msg, data) {
        if (typeof status !== 'boolean' && typeof status !== 'number') {
            status = false;
        }
        if (typeof msg !== 'string') {
            msg = '';
        }
        return {
            'status': status,
            'msg': msg,
            'data': data
        };
    }
}


/* 获取设备信息 */
const getDevInfo = () => {
    return new Promise((result) => {
        var _this = this;
        let netType = '';
        uni.getNetworkType({
            success: function (res) {
                netType = res.networkType
                uni.getSystemInfo({
                    success: function (res) {
                        let appVersion = '1.0.0';
                        // #ifdef MP-WEIXIN
                        let ver = wx.getAccountInfoSync();
                        appVersion = (ver.miniProgram.version != '') ? ver
                            .miniProgram.version :
                            '1.0.0';
                        // #endif
                        let tickForm = {
                            issue_type: 'multi', //
                            os: res.platform,
                            app: 'wanpi',
                            model: res.model, // 手机机型
                            channel: 'official_mini1', // 渠道码
                            deviceId: res.deviceId, // 手机设备ID
                            appVersion: appVersion, // 小程序版本号
                            osVersion: res.system, // 手机系统版本
                            netType: (netType == 'wifi') ? '2' : '1', //网络类型
                            ispType: '', //运营商类型
                            pub_timestamp: new Date().getTime(),
                            pub_sign: ''
                        }
                        store.commit('SETPUBLICCOUNSEL', tickForm);
                        console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>在这里设置了公参")
                        result(tickForm);
                    },
                    fail(err) {
                        uni.showToast({
                            title: '意外错误',
                            icon: 'error'
                        });
                    }
                });
            },
            fail(err) {
                uni.showToast({
                    title: '意外错误',
                    icon: 'error'
                });
            }
        });
    })
}


request.globalRequest = async (url, method, data, power) => {
    /*     权限判断 因为有的接口请求头可能需要添加的参数不一样，所以这里做了区分
    == 不通过access_token校验的接口
    == 文件下载接口列表
    == 验证码登录 */
    let dataObj = data;
    if (!store.state.publicCounsel.os) {
        await getDevInfo();
    }
    dataObj = {
        ...data,
        ...store.state.publicCounsel
    }
    switch (power) {
        case 1:
            headers['content-type'] = 'application/x-www-form-urlencoded'
            headers['access_token'] = (store.state.identity.access_token) ? `${store.state.identity.access_token}` :
                ''
            headers['pub_ticket'] = (store.state.tickets.length > 0) ? `${store.state.tickets[0].ticket}` : ''
            headers['pub_uid'] = (store.state.identity.uid) ? `${store.state.identity.uid}` : ''
            break;
        case 2:
            headers['Authorization'] = 'Basic a3N1ZGlfcGM6a3N1ZGlfcGM='
            break;
        case 3:
            responseType = 'blob'
            break;
        default:
            headers['content-type'] = 'application/json'
            headers['access_token'] = (store.state.identity.access_token) ? `${store.state.identity.access_token}` :
                ''
            headers['pub_ticket'] = (store.state.tickets.length > 0) ? `${store.state.tickets[0].ticket}` : ''
            headers['pub_uid'] = (store.state.identity.uid) ? `${store.state.identity.uid}` : ''
            break;
    }

    return uni.request({
        url: urlConfig + url,
        method,
        data: dataObj,
        dataType: 'json',
        header: headers
    }).then(res => {
        if (res[1].data && res[1].data.code + '' === '401') {
            store.commit('LOGOUT');
            uni.reLaunch({
                url: '/pages/login/login',
                fail(err) {
                    console.log(err)
                }
            })
        }
        if (res[1].data.code + '' !== '200') {
            uni.showToast({
                title: res[1].data.message,
                icon: 'none'
            })
        }

        return res[1].data;
    }).catch(parmas => {
        uni.showToast({
            title: "网络异常",
            icon: 'error'
        })
    })
}

export default request
